<?php

namespace app\admin\controller\printmanager;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 印刷需求管理
 *
 * @icon fa fa-circle-o
 */
class Printing extends Backend
{
    
    /**
     * Printing模型对象
     * @var \app\common\model\printmanager\Printing
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\printmanager\Printing;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("displayList", $this->model->getDisplayList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                // $row->visible(['id','user_id','title','category_id','used_time','linkname','telephone','status','address','createtime']);
                $row->org_info = $row->org_info;
                $row->product_info = $row->product_info;
                $row->designer_info = $row->designer_info;
                $row->design_product_info = $row->design_product_info;
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 分配印刷机构
     */
    public function setorg($ids){
        if($this->request->isPost()){
            
            Db::startTrans();

            $item = $this->model->get($ids);
            if(!$item){
                Db::rollback();
                $this->error("需求不存在");
            }
            if($item->org_id){
                Db::rollback();
                $this->error("已经设置过");
            }
            if($item->status!=3){
                Db::rollback();
                $this->error("需求状态错误");
            }

            $data = $this->request->param('row/a');

            if(!isset($data['org_id']) || empty($data['org_id'])){
                Db::rollback();
                $this->error("请选择合作商");
            }

            $org = \app\common\model\printmanager\Org::get($data['org_id']);

            if(!$org || $org->status!=1){
                Db::rollback();
                $this->error("请选择合法的合作商");
            }

            $item->org_id = $data['org_id'];
            
            if($item->save() === false){
                Db::rollback();
                $this->error("操作失败");
            }

            $pro = \app\common\model\printmanager\Production::create([
                'pringting_id' => $item->id,
                'org_id' => $item->org_id,
                'amount' => isset($data['amount']) ? $data['amount'] : 0,
            ]);

            if(!$pro){
                Db::rollback();
                $this->error("操作失败");
            }

            Db::commit();
            $this->success("操作成功");
            
        }
        return $this->edit($ids);
    }


    /**
     * 分配设计师
     */
    public function setdesigner($ids){
        if($this->request->isPost()){
            
            Db::startTrans();

            $item = $this->model->get($ids);
            if(!$item){
                Db::rollback();
                $this->error("需求不存在");
            }
            if($item->designer_id){
                Db::rollback();
                $this->error("已经设置过");
            }
            if($item->status!=3){
                Db::rollback();
                $this->error("需求状态错误");
            }

            $data = $this->request->param('row/a');

            if(!isset($data['designer_id']) || empty($data['designer_id'])){
                Db::rollback();
                $this->error("请选择设计师");
            }

            $org = \app\common\model\designermanager\Designer::get($data['designer_id']);

            if(!$org || $org->status!=1){
                Db::rollback();
                $this->error("请选择合法的设计师");
            }

            $item->designer_id = $data['designer_id'];
            
            if($item->save() === false){
                Db::rollback();
                $this->error("操作失败");
            }

            $pro = \app\common\model\designermanager\Production::create([
                'pringting_id' => $item->id,
                'designer_id' => $item->designer_id,
                'amount' => isset($data['amount']) ? $data['amount'] : 0,
            ]);

            if(!$pro){
                Db::rollback();
                $this->error("操作失败");
            }

            Db::commit();
            $this->success("操作成功");
            
        }
        return $this->edit($ids);
    }

     /**
     * 任务完成
     */
    public function done($ids){
        Db::startTrans();

        $item = $this->model->get($ids);
        if(!$item){
            Db::rollback();
            $this->error("需求不存在");
        }
        if($item->status!=3){
            Db::rollback();
            $this->error("需求状态错误");
        }

        if($item->design_product_info){
            if(!$item->design_product_info->status > 0){
                Db::rollback();
                $this->error("设计任务未完成");
            }
        }

        if($item->product_info){
            if(!$item->product_info->status > 0){
                Db::rollback();
                $this->error("印刷任务未完成");
            }
        }


        $item->status = 4;
        
        if($item->save() === false){
            Db::rollback();
            $this->error("操作失败");
        }

        Db::commit();
        $this->success("操作成功");
    }

    /**
     * 审核
     * @param $ids
     * @param $action refuse/check
     * @param $reason
     */
    public function check($ids, $action = NULL, $reason =''){
        $actions = ['refuse', 'check','paydone'];
        if(!in_array($action, $actions)){
            $this->error('参数错误');
        }
        if($action == 'refuse' && empty($reason)){
            $this->error('请输入审核意见');
        }
        $item = $this->model->get($ids);
        if(!$item){
            $this->error('需求不存在');
        }
        $item->admin_id = $this->auth->id;
        if($action == 'refuse'){
            if($item->status != 0 && $item->status != 1){
                $this->error('该需求已经审核');
            }
            $item->status = 2;
            $item->sudit_opinion = $reason;
        }elseif($action=='check'){
            if($item->status != 0){
                $this->error('该需求已经审核');
            }
            $item->status = 1;
            $item->display = 1;
            $item->sudit_opinion = $reason;
        }elseif($action=='paydone'){
            if($item->status != 1){
                $this->error('状态错误');
            }
            $item->status = 3;
            $item->display = 1;
            $item->sudit_opinion = $reason;
        }
        if($item->save()){
            $this->success('操作成功');
        }
        $this->error('操作失败');
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
